Hello,
This tutorial shows you laravel create custom artisan command. We will use laravel create custom artisan. you will learn laravel custom artisan command. you can understand a concept of how to create custom artisan command in laravel. So, let’s follow few step to create example of create artisan command laravel.
You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.
Laravel provides its own artisan commands for creating migration, model, controller, etc. but if you want to create your own artisan command for project setup, admins users, etc. then I will help you how to create a custom artisan command in laravel application.
In this example, we will create custom “php artisan create:users” command using laravel artisan command. Command will take one argument in integer. Then we will create users using factory based on command argument.
so let’s follow the below step to create your owl artisan command in laravel app.
Step 1: Install Laravel
first of all we need to get fresh Laravel version application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project laravel/laravel example-app
Step 2: Database Configuration
In this step, we need to add database configuration in .env file. so let’s add following details and then run migration command:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel9_blog
DB_USERNAME=root
DB_PASSWORD=password
Next, run migration command to create users table.
php artisan migrate
Step 3: Generate Artisan Command
In this step, we need to create “CreateUsers” class using following command. Then copy below code into it. we will add “create-users” command name.
php artisan make:command CreateUsers
Then let’s update following command file.
app/Console/Commands/CreateUsers.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\User;
class CreateUsers extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'create:users {count}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create Dummy Users for your App';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$numberOfUsers = $this->argument('count');
for ($i = 0; $i < $numberOfUsers; $i++) {
User::factory()->create();
}
return 0;
}
}
Step 4: Use Created Artisan Command
In this step, we will run our custom command and check artisan command using “php artisan list” command.
So, let’s run following custom command to create multiple users:
php artisan create:users 10
php artisan create:users 5
You can check in your users table, it will created records there.
Next, you can check your custom command on list as well.
php artisan list
Output:
I hope it can help you…